<template>
  <div class="app_content_container">
    <Breadcrumb :items="['标签管理']" />
    <BaseTable
      ref="baseTableRef"
      :apiUrl="getLabelList"
      :columns="columns"
      placeholder="请输入名称"
      height="calc(100vh - 180px)"
      :isShowAddBtn="false"
      isRowSelection
      @handleSelectionChange="(val) => (selectedKeys = val)"
    >
      <template #operatBtns>
        <ga-button
          type="primary"
          @click="$refs.addOrEditRef.open()"
          style="margin-right: 8px"
          >创建</ga-button
        >
        <ga-button
          status="danger"
          @click="handleDelete(selectedKeys)"
          :disabled="isdisable"
        >
          批量删除
        </ga-button>
      </template>
      <template #required="{ record }">
        <ga-switch
          size="mini"
          v-model="record.required"
          @change="handleEnabledChange(record)"
        />
      </template>
      <template #action="{ record }">
        <ga-link @click="$refs.addOrEditRef.open(record)">编辑</ga-link>
        <ga-link status="danger" @click="handleDelete([record])">删除</ga-link>
      </template>
    </BaseTable>
    <addOrEdit ref="addOrEditRef" @fetchData="$refs.baseTableRef.fetchData()" />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { columns } from "./columns";
import { getLabelList, deleteLabel, editRequired } from "@/api/tagMgmt";
import { warningModal } from "@/hooks/useWarningModal";
import addOrEdit from "./addOrEdit.vue";
import { Message } from "@garco-design/web-vue";

const selectedKeys = ref([]);
const isdisable = computed(() => selectedKeys.value?.length === 0);
// 删除方法
const baseTableRef = ref(null);
const handleDelete = async (records) => {
  const ids = records.map((item) => ({ id: item?.id ? item.id : item }));
  warningModal(`确定要删除数据吗`, async () => {
    try {
      await deleteLabel(ids);
      Message.success("操作成功");
      baseTableRef.value.fetchData();
    } catch (err) {
      console.log(err);
    }
  });
};
// 处理方法
const handleEnabledChange = async (record) => {
  try {
    await editRequired(record?.id, { required: record?.required });
    Message.success("操作成功");
  } catch (error) {
    baseTableRef.value.fetchData();
  }
};
</script>

<style lang="scss" scoped></style>
